<template>
  <div class="order-page" :class="{ 'debug': debugMode }">
    <!-- 音频通知组件 -->
    <AudioNotification ref="audioNotificationRef" />
    
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">订单管理</h2>
        <span class="title-desc">管理餐厅的所有订单</span>
      </div>
      <div class="order-stats">
        <div class="stat-item" @click="handleStatusChange(ORDER_STATUS.TO_BE_CONFIRMED)">
          <div class="stat-value waiting">{{ statusCounts[ORDER_STATUS.TO_BE_CONFIRMED] || 0 }}</div>
          <div class="stat-label">待接单</div>
        </div>
        <div class="stat-item" @click="handleStatusChange(ORDER_STATUS.CONFIRMED)">
          <div class="stat-value processing">{{ statusCounts[ORDER_STATUS.CONFIRMED] || 0 }}</div>
          <div class="stat-label">待派送</div>
        </div>
        <div class="stat-item" @click="handleStatusChange(ORDER_STATUS.DELIVERY_IN_PROGRESS)">
          <div class="stat-value delivery">{{ statusCounts[ORDER_STATUS.DELIVERY_IN_PROGRESS] || 0 }}</div>
          <div class="stat-label">派送中</div>
        </div>
      </div>
    </div>

    <div class="content-card">
      <!-- 订单状态标签页 -->
      <div class="status-tabs">
        <div class="tab-list">
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === '' }"
            @click="handleStatusChange('')"
          >
            全部订单
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.PENDING_PAYMENT }"
            @click="handleStatusChange(ORDER_STATUS.PENDING_PAYMENT)"
          >
            待付款
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.TO_BE_CONFIRMED }"
            @click="handleStatusChange(ORDER_STATUS.TO_BE_CONFIRMED)"
          >
            待接单
            <span 
              class="count-bubble" 
              v-show="statusCounts[ORDER_STATUS.TO_BE_CONFIRMED] > 0"
            >{{ statusCounts[ORDER_STATUS.TO_BE_CONFIRMED] }}</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.CONFIRMED }"
            @click="handleStatusChange(ORDER_STATUS.CONFIRMED)"
          >
            待派送
            <span 
              class="count-bubble" 
              v-show="statusCounts[ORDER_STATUS.CONFIRMED] > 0"
            >{{ statusCounts[ORDER_STATUS.CONFIRMED] }}</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.DELIVERY_IN_PROGRESS }"
            @click="handleStatusChange(ORDER_STATUS.DELIVERY_IN_PROGRESS)"
          >
            派送中
            <span 
              class="count-bubble" 
              v-show="statusCounts[ORDER_STATUS.DELIVERY_IN_PROGRESS] > 0"
            >{{ statusCounts[ORDER_STATUS.DELIVERY_IN_PROGRESS] }}</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.COMPLETED }"
            @click="handleStatusChange(ORDER_STATUS.COMPLETED)"
          >
            已完成
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeStatus === ORDER_STATUS.CANCELLED }"
            @click="handleStatusChange(ORDER_STATUS.CANCELLED)"
          >
            已取消
          </div>
          <!-- 已移除拒单状态选项卡 -->
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchParams" class="search-form">
          <el-form-item label="订单号">
            <el-input 
              v-model="searchParams.number" 
              placeholder="请输入订单号"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input 
              v-model="searchParams.phone" 
              placeholder="请输入手机号"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
              :disabled-date="disabledDate"
              class="date-picker"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchOrders" class="search-btn">
              <el-icon><Search /></el-icon>查询
            </el-button>
            <el-button @click="resetSearch" class="search-btn">
              <el-icon><RefreshRight /></el-icon>重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 订单数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="orderList"
          style="width: 100%"
          border
          :header-cell-style="{background:'#f9f9fa', color: '#303133', fontWeight: '500'}"
          :row-class-name="(_, rowIndex) => rowIndex % 2 === 0 ? 'row-even' : 'row-odd'"
          empty-text="暂无订单数据"
          highlight-current-row
        >
          <template #empty>
            <div class="empty-state">
              <el-icon size="48" color="#C0C4CC">
                <Document />
              </el-icon>
              <p class="empty-text">暂无订单数据</p>
              <p class="empty-desc">当前筛选条件下没有找到相关订单</p>
            </div>
          </template>
          <el-table-column prop="number" label="订单号" min-width="180" show-overflow-tooltip>
            <template #default="{row}">
              <div class="order-number-wrapper">
                <span class="order-number">{{ row.number }}</span>
                <el-tag v-if="row.isUrged" type="warning" size="small" effect="dark" class="urged-tag">
                  <el-icon><WarningFilled /></el-icon>
                  催单
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单状态" width="120" align="center">
            <template #default="{row}">
              <el-tag :type="getStatusTagType(row.status)" effect="light">
                {{ getOrderStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="支付状态" width="100" align="center">
            <template #default="{row}">
              <el-tag 
                :type="row.payStatus === PAYMENT_STATUS.PAID ? 'success' : row.payStatus === PAYMENT_STATUS.REFUNDED ? 'info' : 'danger'"
                effect="plain"
              >
                {{ getPaymentStatusText(row.payStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="consignee" label="收货人" width="100"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="130"></el-table-column>
          <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip></el-table-column>
          <el-table-column label="金额" width="100" align="right">
            <template #default="{row}">
              <span class="amount">￥{{ formatPrice(row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderTime" label="下单时间" width="180"></el-table-column>
          <el-table-column label="操作" fixed="right" width="220" align="center">
            <template #default="{row}">
              <div class="action-buttons">
                <!-- 待付款状态 -->
                <template v-if="row.status === ORDER_STATUS.PENDING_PAYMENT">
                  <el-button link type="warning" @click="handleCancelOrder(row)" class="action-btn">
                    <el-icon><WarningFilled /></el-icon>取消
                  </el-button>
                </template>
                
                <!-- 待接单状态 -->
                <template v-if="row.status === ORDER_STATUS.TO_BE_CONFIRMED">
                  <el-button link type="primary" @click="handleConfirmOrder(row)" class="action-btn">
                    <el-icon><Check /></el-icon>接单
                  </el-button>
                  <el-button link type="danger" @click="handleRejectOrder(row)" class="action-btn">
                    <el-icon><Close /></el-icon>拒单
                  </el-button>
                </template>
                
                <!-- 已接单状态 -->
                <template v-if="row.status === ORDER_STATUS.CONFIRMED">
                  <el-button link type="primary" @click="handleDeliverOrder(row)" class="action-btn">
                    <el-icon><Van /></el-icon>派送
                  </el-button>
                  <el-button link type="warning" @click="handleCancelOrder(row)" class="action-btn">
                    <el-icon><WarningFilled /></el-icon>取消
                  </el-button>
                </template>
                
                <!-- 派送中状态 -->
                <template v-if="row.status === ORDER_STATUS.DELIVERY_IN_PROGRESS">
                  <el-button link type="primary" @click="handleCompleteOrder(row)" class="action-btn">
                    <el-icon><Check /></el-icon>完成
                  </el-button>
                  <el-button link type="warning" @click="handleCancelOrder(row)" class="action-btn">
                    <el-icon><WarningFilled /></el-icon>取消
                  </el-button>
                </template>
                
                <!-- 已完成状态 - 添加取消按钮 -->
                <template v-if="row.status === ORDER_STATUS.COMPLETED">
                  <el-button link type="warning" @click="handleCancelOrder(row)" class="action-btn">
                    <el-icon><WarningFilled /></el-icon>取消
                  </el-button>
                </template>
                
                <!-- 查看按钮（所有状态都显示） -->
                <el-button link type="info" @click="viewOrderDetail(row)" class="action-btn">
                  <el-icon><View /></el-icon>查看
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <span class="total-info">共 {{ total }} 条记录</span>
          <span class="page-info">第 {{ currentPage }} 页，共 {{ Math.ceil(total / pageSize) || 1 }} 页</span>
        </div>
        <div class="pagination-controls">
          <el-pagination
            background
            layout="sizes, prev, pager, next, jumper"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :hide-on-single-page="false"
          />
        </div>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <OrderDetail
      v-model:visible="detailDialogVisible"
      :order-id="currentOrderId"
      @refresh="fetchOrderList"
    />

    <!-- 拒单原因弹窗 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒单原因"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules">
        <el-form-item prop="rejectionReason" label="拒单原因" label-width="100px">
          <el-select
            v-model="rejectForm.rejectionReason"
            placeholder="请选择拒单原因"
            style="width: 100%"
            :teleported="false"
          >
            <el-option label="商品已售完" value="商品已售完" />
            <el-option label="超出配送范围" value="超出配送范围" />
            <el-option label="店铺已打烊" value="店铺已打烊" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 取消原因弹窗 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="500px"
      destroy-on-close
      class="custom-dialog"
      append-to-body
    >
      <el-form :model="cancelForm" ref="cancelFormRef" :rules="cancelRules">
        <el-form-item prop="cancelReason" label="取消原因" label-width="100px">
          <el-select
            v-model="cancelForm.cancelReason"
            placeholder="请选择取消原因"
            style="width: 100%"
            @change="handleCancelReasonChange"
            :teleported="false"
          >
            <el-option label="商品已售完" value="商品已售完" />
            <el-option label="顾客取消" value="顾客取消" />
            <el-option label="店铺已打烊" value="店铺已打烊" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="cancelForm.cancelReason === '其他原因'" 
          prop="customCancelReason" 
          label="具体原因" 
          label-width="100px"
        >
          <el-input
            v-model="cancelForm.customCancelReason"
            type="textarea"
            :rows="3"
            placeholder="请输入具体的取消原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { Document, Phone, Search, RefreshRight, Check, Close, View, Van, WarningFilled } from '@element-plus/icons-vue'
import OrderDetail from './components/OrderDetail.vue'
import { 
  ORDER_STATUS, 
  PAYMENT_STATUS, 
  ORDER_STATUS_TEXT, 
  PAYMENT_STATUS_TEXT,
  ORDER_STATUS_TAG_TYPE
} from './constants'
import orderAPI from '@/api/order'
import { initWebSocket } from '@/utils/websocket'
import AudioNotification from '@/components/AudioNotification.vue'

const router = useRouter()

// axios实例
const authAxios = axios.create({
  baseURL: '/api',  // 改为使用/api前缀的相对路径
  timeout: 10000
})

// 存储token的位置，可能在localStorage或sessionStorage
const getToken = () => {
  return localStorage.getItem('token') || sessionStorage.getItem('token')
}

// 检查是否有token，没有则跳转登录
const checkToken = () => {
  const token = getToken()
  if (!token) {
    ElMessage.warning('登录已过期，请重新登录')
    router.push('/login')
    return false
  }
  return true
}

// 请求拦截器加token
authAxios.interceptors.request.use(
  config => {
    // 从本地存储获取token
    const token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
authAxios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      if (error.response.status === 401) {
        ElMessage.error('登录状态已失效，请重新登录')
        // 清除token并跳转到登录页
        localStorage.removeItem('token')
        sessionStorage.removeItem('token')
        router.push('/login')
      } else {
        const msg = error.response.data.msg || '请求失败'
        ElMessage.error(msg)
      }
    } else {
      ElMessage.error('网络异常，请稍后重试')
    }
    return Promise.reject(error)
  }
)

// 数据查询参数
const searchParams = reactive({
  number: '',   // 订单号
  phone: '',    // 手机号
  status: '',   // 订单状态
  beginTime: '', // 开始时间
  endTime: '',   // 结束时间
  page: 1,
  pageSize: 10
})

// 日期范围
const dateRange = ref([])

// 表格数据
const orderList = ref([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const activeStatus = ref('')

// 状态数量统计
const statusCounts = ref({})

// 详情对话框
const detailDialogVisible = ref(false)
const currentOrderId = ref(null)

// 拒单对话框状态
const rejectDialogVisible = ref(false)
const rejectFormRef = ref(null)
const rejectForm = reactive({
  id: null,
  rejectionReason: ''
})
const rejectRules = {
  rejectionReason: [
    { required: true, message: '请选择拒单原因', trigger: 'change' }
  ]
}

// 取消订单对话框状态
const cancelDialogVisible = ref(false)
const cancelFormRef = ref(null)
const cancelForm = reactive({
  id: null,
  cancelReason: '',
  customCancelReason: ''
})
const cancelRules = {
  cancelReason: [
    { required: true, message: '请选择取消原因', trigger: 'change' }
  ],
  customCancelReason: [
    { 
      required: true, 
      message: '请输入具体的取消原因', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (cancelForm.cancelReason === '其他原因' && !value) {
          callback(new Error('请输入具体的取消原因'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 设置开发调试相关变量
const debugMode = ref(false);
const useTestData = ref(false); // 设置为false不使用测试数据

// 定时刷新计时器
let statsRefreshInterval = null;

// 音频组件引用
const audioNotificationRef = ref(null)

// 存储被催单的订单ID
const urgedOrders = ref(new Set())

// 监听日期范围变化
watch(dateRange, (val) => {
  if (val && val.length === 2) {
    searchParams.beginTime = val[0]
    searchParams.endTime = val[1]
  } else {
    searchParams.beginTime = ''
    searchParams.endTime = ''
  }
})

// 获取订单列表
const fetchOrderList = async () => {
  loading.value = true
  try {
    const res = await authAxios.get('/admin/order/conditionSearch', {
      params: {
        ...searchParams,
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.data.code === 1) {
      // 为每个订单添加催单状态
      const orders = res.data.data.records || []
      orderList.value = orders.map(order => ({
        ...order,
        isUrged: urgedOrders.value.has(order.id) || urgedOrders.value.has(order.number)
      }))
      total.value = res.data.data.total || 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取各状态订单数量
const fetchOrderCounts = async () => {
  try {
    // 使用API模块从后端获取数据
    console.log('获取订单统计数据');
    const res = await orderAPI.getOrderStatistics();
    
    if (res && res.code === 1) {
      handleOrderStatistics(res.data);
    } else {
      console.error('获取订单统计数据失败:', res?.msg || '未知错误');
    }
  } catch (error) {
    console.error('订单统计请求异常:', error);
  }
}

// 处理订单统计数据，将其映射到状态计数对象
const handleOrderStatistics = (data) => {
  if (!data) {
    console.error('订单统计数据为空');
    return;
  }
  
  // 将后端返回的数据映射到对应的状态值
  statusCounts.value = {
    1: data.pendingPayment || 0,      // 待付款
    2: data.toBeConfirmed || 0,      // 待接单
    3: data.confirmed || 0,          // 已接单
    4: data.deliveryInProgress || 0, // 派送中
    5: data.completed || 0,          // 已完成
    6: data.cancelled || 0           // 已取消
  };
}

// 处理状态切换
const handleStatusChange = (status) => {
  activeStatus.value = status
  searchParams.status = status
  currentPage.value = 1
  fetchOrderList()
  
  // 记录到控制台，用于调试
  console.log('切换到状态:', status, '数据:', {
    activeStatus: activeStatus.value,
    searchParams: {...searchParams},
    statusCounts: {...statusCounts.value}
  })
}

// 搜索订单
const searchOrders = () => {
  currentPage.value = 1
  fetchOrderList()
}

// 重置搜索条件
const resetSearch = () => {
  searchParams.number = ''
  searchParams.phone = ''
  searchParams.beginTime = ''
  searchParams.endTime = ''
  // 不重置状态，因为用户可能在某个标签页下进行操作
  dateRange.value = []
  currentPage.value = 1
  fetchOrderList()
}

// 日期禁用
const disabledDate = (time) => {
  return time > new Date()
}

// 分页切换
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrderList()
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchOrderList()
}

// 查看订单详情
const viewOrderDetail = (row) => {
  currentOrderId.value = row.id
  detailDialogVisible.value = true
}

// 接单处理
const handleConfirmOrder = async (row) => {
  if (!checkToken()) return
  
  try {
    await authAxios.put('/admin/order/confirm', { id: row.id })
    ElMessage.success('接单成功')
    await fetchOrderCounts()
    fetchOrderList()
  } catch (error) {
    console.error('接单失败:', error)
  }
}

// 拒单处理
const handleRejectOrder = (row) => {
  rejectForm.id = row.id
  rejectDialogVisible.value = true
}

// 确认拒单
const confirmReject = async () => {
  rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await authAxios.put('/admin/order/rejection', { id: rejectForm.id, rejectionReason: rejectForm.rejectionReason })
        ElMessage.success('拒单成功')
        rejectDialogVisible.value = false
        fetchOrderCounts()
        fetchOrderList()
      } catch (error) {
        console.error('拒单失败:', error)
      }
    }
  })
}

// 取消订单处理
const handleCancelOrder = (row) => {
  cancelForm.id = row.id
  cancelForm.cancelReason = ''
  cancelForm.customCancelReason = ''
  cancelDialogVisible.value = true
}

// 确认取消订单
const confirmCancel = async () => {
  cancelFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 如果选择的是其他原因，使用自定义理由
        const cancelReason = cancelForm.cancelReason === '其他原因' 
          ? cancelForm.customCancelReason 
          : cancelForm.cancelReason
          
        await authAxios.put('/admin/order/cancel', { 
          id: cancelForm.id, 
          cancelReason: cancelReason 
        })
        ElMessage.success('取消订单成功')
        cancelDialogVisible.value = false
        fetchOrderCounts()
        fetchOrderList()
      } catch (error) {
        console.error('取消订单失败:', error)
      }
    }
  })
}

// 处理取消原因变化
const handleCancelReasonChange = () => {
  // 清空自定义理由输入
  if (cancelForm.cancelReason !== '其他原因') {
    cancelForm.customCancelReason = ''
  }
}

// 派送订单
const handleDeliverOrder = async (row) => {
  if (!checkToken()) return
  
  try {
    await authAxios.put(`/admin/order/delivery/${row.id}`)
    ElMessage.success('订单已派送')
    fetchOrderCounts()
    fetchOrderList()
  } catch (error) {
    console.error('派送订单失败:', error)
  }
}

// 完成订单
const handleCompleteOrder = async (row) => {
  if (!checkToken()) return
  
  try {
    await authAxios.put(`/admin/order/complete/${row.id}`)
    ElMessage.success('订单已完成')
    fetchOrderCounts()
    fetchOrderList()
  } catch (error) {
    console.error('完成订单失败:', error)
  }
}

// 格式化价格
const formatPrice = (price) => {
  return parseFloat(price).toFixed(2)
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  return ORDER_STATUS_TEXT[status] || '未知状态'
}

// 获取支付状态文本
const getPaymentStatusText = (status) => {
  return PAYMENT_STATUS_TEXT[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  return ORDER_STATUS_TAG_TYPE[status] || 'info'
}

// 获取存储的用户ID
const getStoredUserId = () => {
  return localStorage.getItem('userId') || sessionStorage.getItem('userId') || 'admin';
}

// 组件挂载时初始化
onMounted(() => {
  fetchOrderList()
  fetchOrderCounts()
  checkUrlForOrderId() // 检查URL中是否有订单ID
  
  // 启动定时刷新状态计数
  statsRefreshInterval = setInterval(fetchOrderCounts, 30000); // 每30秒刷新一次状态计数
  
  // 添加WebSocket连接和事件处理
  initWebSocket(getStoredUserId(), handleWebSocketMessage);
  
  // 添加订单详情查看事件监听
  window.addEventListener('open-order-detail', handleOrderDetailEvent);
  
  // 注册浏览器刷新前的清理函数
  window.addEventListener('beforeunload', cleanupBeforeUnload);
  
  diagnoseNetworkEnvironment() // 诊断网络环境
})

// 组件销毁时清理
onUnmounted(() => {
  // 清除定时刷新
  if (statsRefreshInterval) {
    clearInterval(statsRefreshInterval)
  }
  
  // 移除事件监听器
  window.removeEventListener('open-order-detail', handleOrderDetailEvent);
  window.removeEventListener('beforeunload', cleanupBeforeUnload);
})

// 浏览器刷新前的清理函数
const cleanupBeforeUnload = () => {
  if (statsRefreshInterval) {
    clearInterval(statsRefreshInterval)
  }
}

// 处理WebSocket消息
const handleWebSocketMessage = (message) => {
  console.log('订单页面收到WebSocket消息:', message);
  
  // 判断消息类型并播放对应音效
  if (message.type === 1 || message.type === 'newOrder') {
    // 新订单音效
    if (audioNotificationRef.value) {
      audioNotificationRef.value.playNotificationSound()
    }
    
    // 刷新订单列表和统计数据
    fetchOrderCounts();
    if (activeStatus.value === ORDER_STATUS.TO_BE_CONFIRMED || activeStatus.value === '') {
      fetchOrderList();
    }
  } else if (message.type === 2 || message.type === 'reminder') {
    // 催单音效
    if (audioNotificationRef.value) {
      audioNotificationRef.value.playReminderSound()
    }
    
    // 处理催单通知
    if (message.orderId) {
      urgedOrders.value.add(message.orderId)
    }
    if (message.orderNumber) {
      urgedOrders.value.add(message.orderNumber)
    }
    
    // 刷新订单列表
    fetchOrderCounts();
    fetchOrderList();
  }
};

// 处理订单详情查看事件
const handleOrderDetailEvent = (event) => {
  if (event && event.detail && event.detail.orderId) {
    console.log('处理订单详情查看事件:', event.detail.orderId);
    currentOrderId.value = event.detail.orderId;
    detailDialogVisible.value = true;
  }
};

// 检查URL中的订单ID参数
const checkUrlForOrderId = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const orderId = urlParams.get('orderId');
  const openDetail = urlParams.get('openDetail');
  
  if (orderId) {
    console.log('检测到URL中的订单ID参数:', orderId);
    
    // 清理URL参数，避免刷新时重复打开
    const newUrl = window.location.pathname;
    window.history.replaceState({}, document.title, newUrl);
    
    // 延迟一点执行，确保页面和数据已经加载
    setTimeout(() => {
      handleViewOrderById(orderId, openDetail === 'true');
    }, 500);
  }
}

// 根据订单ID查看订单详情
const handleViewOrderById = async (orderId, autoOpen = false) => {
  if (!checkToken() || !orderId) return
  
  try {
    console.log('准备打开订单详情，订单ID:', orderId)
    
    // 先检查订单是否存在于当前列表中
    const existingOrder = orderList.value.find(order => order.id == orderId || order.number == orderId)
    
    if (!existingOrder) {
      // 如果当前列表中没有该订单，先刷新订单列表
      console.log('当前列表中未找到订单，正在刷新订单列表...')
      await fetchOrderList()
    }
    
    // 设置订单ID
    currentOrderId.value = orderId
    
    if (autoOpen) {
      // 使用nextTick确保数据更新后再打开对话框
      await nextTick()
      detailDialogVisible.value = true
      console.log('订单详情对话框已打开，订单ID:', orderId)
    }
  } catch (e) {
    console.error('打开订单详情错误:', e)
    ElMessage.error('打开订单详情失败: ' + (e.message || '未知错误'))
  }
}

// 帮助函数：打印浏览器网络环境
const diagnoseNetworkEnvironment = () => {
  console.log('=== 网络环境诊断 ===')
  console.log('当前URL:', window.location.href)
  console.log('网络状态:', navigator.onLine ? '在线' : '离线')
  if (window.location.protocol === 'https:') {
    console.log('警告: 当前是HTTPS协议，但可能在访问HTTP后端，这可能导致混合内容被阻止')
  }
  console.log('浏览器:', navigator.userAgent)
  console.log('=== 诊断结束 ===')
}
</script>

<style>
/* 页面头部和标题样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  border-left: 4px solid #409EFF;
  padding-left: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.title-desc {
  font-size: 14px;
  color: #606266;
}

/* 订单统计区域 */
.order-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 0 15px;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 5px;
}

.waiting {
  color: #E6A23C;
}

.processing {
  color: #409EFF;
}

.delivery {
  color: #67C23A;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

/* 订单管理页面整体样式 */
.order-page {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #fff;
}

.content-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  overflow: hidden;
}

/* 状态标签栏样式 */
.status-tabs {
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #fff;
}

.tab-list {
  display: flex;
  position: relative;
  flex-wrap: wrap; /* 允许在小屏幕上换行 */
  background-color: #fff;
  border-radius: 4px 4px 0 0;
}

.tab-item {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
  display: flex;
  align-items: center;
  color: #606266;
  transition: all 0.3s;
  border-right: 1px solid #f0f0f0;
}

.tab-item {
  position: relative;
  transition: all 0.3s ease;
}

.tab-item:hover {
  color: #409EFF;
  background-color: rgba(64, 158, 255, 0.15);
}

.tab-item.active {
  color: #409EFF;
  font-weight: 500;
  background-color: rgba(64, 158, 255, 0.2);
  border-bottom: 2px solid #409EFF;
}

.tab-text {
  margin-right: 5px;
}

/* 全新设计的红色气泡 */
.tab-item {
  position: relative; /* 确保能相对于此元素定位红泡泡 */
  overflow: visible; /* 确保气泡可以溢出显示 */
  padding-right: 25px; /* 为气泡预留空间 */
}

.count-bubble {
  position: absolute;
  top: 2px;
  right: 8px;
  min-width: 18px;
  height: 18px;
  padding: 0 4px;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: 500;
  line-height: 18px;
  text-align: center;
  border-radius: 9px;
  z-index: 10; /* A确保在顶层 */
  transform: none; /* 移除transform，使位置更可预测 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 28px;
}

/* 搜索区域样式 */
.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

/* 表格区域样式 */
.table-container {
  margin-bottom: 0;
  border-radius: 8px 8px 0 0;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

.table-container :deep(.el-table) {
  border-radius: 8px 8px 0 0;
}

.table-container :deep(.el-table__body-wrapper) {
  border-radius: 0;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.empty-text {
  margin: 16px 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.empty-desc {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

/* 分页器样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0;
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

.pagination-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  color: #606266;
  font-size: 14px;
}

.total-info {
  font-weight: 600;
  color: #303133;
}

.page-info {
  font-size: 12px;
  color: #909399;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

/* 响应式分页器 */
@media (max-width: 768px) {
  .pagination-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .pagination-info {
    text-align: center;
  }
  
  .pagination-controls {
    justify-content: center;
  }
  
  .pagination-controls :deep(.el-pagination) {
    justify-content: center;
  }
}

/* 订单号样式 */
.order-number {
  font-family: monospace;
  font-weight: 500;
}

/* 金额样式 */
.amount {
  font-weight: 500;
  color: #f56c6c;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  position: relative;
  z-index: 100; /* 确保操作按钮在最上层 */
}

.action-btn {
  min-width: 36px;
  padding: 0 4px;
  font-weight: 500;
  background: none !important;
  border: none !important;
  box-shadow: none !important;
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 13px;
  transition: background 0.2s, color 0.2s;
  border-radius: 4px;
  height: 24px;
  line-height: 22px;
  position: relative; /* 确保按钮可以被点击 */
  z-index: 101; /* 确保按钮在最上层 */
}

/* 操作按钮样式 */
.op-green {
  color: #67c23a;
}

.op-orange {
  color: #e6a23c;
}

.op-blue {
  color: #409eff;
}

.op-red {
  color: #f56c6c;
}

.op-btn:hover {
  background-color: rgba(0,0,0,0.05) !important;
}

/* 对话框样式 */
.custom-dialog .el-dialog__header {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
}

.custom-dialog .el-dialog__body {
  padding: 20px;
}

.custom-dialog .el-dialog__footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .order-stats {
    margin-top: 20px;
    width: 100%;
  }
  
  .stat-item {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .order-page {
    padding: 16px;
  }
  
  .content-card {
    padding: 16px;
  }
  
  .search-area {
    padding: 16px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .date-picker {
    width: 100%;
  }
}
</style>